/**
 * Created by shenhai on 15/9/14.
 */
/*  宝宝树66小区二次改造    add   gct  20170811   start   */
var systemCancelReasonMessage=mongoose.model('system_cancel_reason_message');
var ambassadorCommunity = mongoose.model('ambassador_community');
/*  宝宝树66小区二次改造    add   gct  20170811   end   */
var async = require('async');
var moment = require('moment');
var Community = mongoose.model('community');
var Region = mongoose.model('masterData_Regions');
var User = mongoose.model('user');
var UserCommunity = mongoose.model('user_community');
var UserAuthentication = mongoose.model('user_authentications');
var UserFollowups = mongoose.model('user_followups');
var RoleApply = mongoose.model('user_role_apply');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var QuestionStore = mongoose.model('question_store');
var Question = mongoose.model('question');
var toolUtil = require('../../../common/utils/toolUtil');
/*  宝宝树66小区三期改造    mod   luolh  20170929   start   */
var Goods = mongoose.model('goods');
var replyIndex = mongoose.model('reply_index');
var GoodsReply = mongoose.model('goods_reply');
var ugcReply = mongoose.model('system_ugcReply');
var os=require('os');
/*  宝宝树66小区三期改造    mod   luolh  20170929   end   */

Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};
/*  宝宝树66小区二次改造    add   gct  20170811   start   */
exports.getCancelReasonMessageListService=function(req, callback) {
    var data = null;
    async.series([
        function(callbackInner)
        {
            /* 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start */
            systemCancelReasonMessage.find({isValid:true, msgType: 0}).sort('msgSort').exec(function(err,results){
                data=results;
                callbackInner(null,data);
            });
            /* 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end */
        }
    ], callback);
};
/*  宝宝树66小区二次改造    add   gct  20170811   end   */

/* 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 start */
// 获取创始人申请拒绝理由信息
exports.getDeclineReasonMessageListService = function(req, callback) {
    var data = null;
    async.series([
        function(callbackInner) {
            systemCancelReasonMessage.find({isValid: true, msgType: 1}).sort('msgSort').exec(function(err,results){
                data=results;
                callbackInner(null,data);
            });
        }
    ], callback);
};
/* 宝宝树66小区 sprint5 创始人申请页面 拒绝用户小区大使申请修改 modify wangcan 20171206 end */

exports.frontUserListService = function (req, callback) {

    var body = req.body;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    var option = body;
    var sortType = {dateCreated: -1};

    if (option.mobilePhone) option.mobilePhone = new RegExp(option.mobilePhone);
    if (option.nickName) option.nickName = new RegExp(option.nickName);

    if (body.startDate || body.endDate) {
        if (body.startDate && body.endDate) {
            if (decodeURI(body.startDate) < decodeURI(body.endDate)) {
                option.dateCreated = {$gte: decodeURI(body.startDate), $lte: decodeURI(body.endDate)};
            }
        } else if (body.startDate) {
            option.dateCreated = {$gte: decodeURI(body.startDate)};
        } else if (body.endDate) {
            option.dateCreated = {$lte: decodeURI(body.endDate)};
        }
    }
    delete option.startDate;
    delete option.endDate;

    logger.debug(option);

    var data = null;

    async.series([
        function (callbackInner) {
            User.count({}, function (err, count) {
                //TODO luolh 系统不一样对象解析不一样？
            // User.count(option, function (err, count) {
                totalPage = Math.ceil(count / size);
                var temp = {count: count, totalPage: totalPage};
                callbackInner(err, temp);

            });
        },
        function (callbackInner) {
            User.find(option).sort(sortType).skip(index).limit(size)
                .populate('community', '_id communityName provinceId cityId countyId')
                .populate('domainOfExpertise', 'value')
                .populate('homeTown.country', 'name')
                .populate('homeTown.province', 'name')
                .populate('homeTown.city', 'name')
                .populate('homeTown.county', 'name')
                .populate('userPortrait', 'value')
                .populate('cityId', 'name')
                .exec(function (err, result) {

                    if (!err) data = result;




                    callbackInner(err, result);
                });
        },

        function (callbackInner) {

            if (data && data.length) {

                async.each(data, function (user, callbackInner2) {

                    async.series([

                        function (callbackInner3) {
                            if (!(user.community && user.community.provinceId)) {
                                callbackInner3();
                            } else {
                                Region.findOne({_id: user.community.provinceId}, function (err, result) {
                                    user.community._doc.provinceName = result.name;
                                    callbackInner3(err, result);
                                });
                            }
                        },

                        function (callbackInner3) {
                            if (!(user.community && user.community.cityId)) {
                                callbackInner3();
                            } else {
                                Region.findOne({_id: user.community.cityId}, function (err, result) {
                                    user.community._doc.cityeName = result.name;
                                    callbackInner3(err, result);
                                });
                            }
                        },

                        function (callbackInner3) {
                            if (!(user.community && user.community.countyId)) {
                                callbackInner3();
                            } else {
                                Region.findOne({_id: user.community.countyId}, function (err, result) {
                                    user.community._doc.countyName = result.name;
                                    callbackInner3(err, result);
                                });
                            }
                        },
                        function (callbackInner3) {

                            UserCommunity.findOne({user: user._id, type: 2}).populate('community', '_id communityName')
                                .exec(function (err, result) {
                                    //logger.debug(result);
                                    //logger.debug(result);
                                    if (result) {
                                        user._doc.parentsCommunity = result.community._id;
                                        user._doc.parentsCommunityName = result.community.communityName;

                                    }
                                    callbackInner3(err, result);
                                });
                        }

                    ], callbackInner2);

                }, function(err){
                    //logger.debug(data);

                    callbackInner(null,data);// must call once
                });

            }else{
                callbackInner(null);
            }

        },

    ], callback);

};

// 修改用户资料
exports.updateInfoService = function (req, callback) {

    var body = req.body;
    var community = body.user.community;
    if (!body.userID) {
        return callback('body参数错误', null);
    }

    /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
    // var community = body.user.community; // 新(局部变量变成全局变量)

    async.series([
        /*  宝宝树66小区二次改造    mod   gct  20170809   start   */
        function(callbackInner)
        {

            //var community = body.user.community;
            // var community = body.user.community; // 旧
            /*  宝宝树66小区二次改造    mod   guo.xiaomin  20170817   start   */
            if(community)
            {
                callbackInner(null,null);
            }
            else {
                Community.findOne({communityName: body.communityValue,isValid : true,cityId:body.user.cityId}, function (err, result) {
                    if(err)
                    {
                        logger.error(err.message);
                        callbackInner(err, result);
                    }
                    /*  宝宝树66小区二次改造    add   gct  20170817   start   */
                    else if(result==null)
                    {
                        return callback({status:999, message:"请仔细确认小区名"}, null);
                    }
                    /*  宝宝树66小区二次改造    add   gct  20170817  end */
                    community= result._id;
                    body.user.community=community;
                    //alert(community);

                    callbackInner(null, null);

                    /* if (!err && isModerator(result.userRole)) {
                     callback();
                     } else {
                     callback('is not moderator...');
                     }*/
                });

                /* alert("小区："+body.communityValue);*/
            }

            /*  宝宝树66小区二次改造    del   gct  20170802   start   */
            // delete  body.user.community;
            /*  宝宝树66小区二次改造    del   gct  20170802   end   */
            logger.debug(body);
        },
        /*  宝宝树66小区二次改造    mod   gct  20170809   end   */
        /*  宝宝树66小区二次改造    mod   gct  20170817   start   */
        /*function (callbackInner) {
            User.findOne({_id: body.userID},function(err, result)
            {
                var oldCommunityId=result.community;
                User.update({_id: body.userID}, body.user, function (err, result) {
                        RoleApply.findOne({user: body.userID,status : 1,community:oldCommunityId},function(err,result)
                        {
                            if(err)
                            {
                                logger.error(err.message);
                                callbackInner(err, result);
                            }
                            else if(result!=null)
                            {
                                RoleApply.update({user: body.userID,status : 1}, {status:-1},{ multi: true },function(err,result)
                                {
                                    if(err)
                                    {
                                        logger.error(err.message);
                                        callbackInner(err, result);
                                    }
                                    else if(result!=null)
                                    {
                                        UserCommunity.remove({user: body.userID, community:oldCommunityId, type: 1}).exec(
                                            function (err, results) {
                                                if(err)
                                                {
                                                    logger.error(err.message);
                                                    callbackInner(err, result);
                                                }
                                                else if(result!=null)
                                                {
                                                    ambassadorCommunity.update({user: body.userID},{isValid:false},{ multi: true },callbackInner);
                                                }
                                            }
                                        );
                                    }

                                });
                            }
                            else if(result==null)
                            {
                                RoleApply.update({user: body.userID,status : 0}, {status:-1},{ multi: true },function(err,result)
                                {
                                    UserCommunity.remove({user: body.userID, community:oldCommunityId, type: 1}).exec(
                                        function (err, results) {
                                            ambassadorCommunity.update({user: body.userID},{isValid:false},{ multi: true },callbackInner);
                                        }
                                    );
                                });
                            }
                        });
                    }
                );
            });


        },*/
        /*  宝宝树66小区二次改造    mod   gct  20170817   end   */
        /*  宝宝树66小区二次改造    mod   gct  20170817   start   */
       /*  宝宝树66小区二次改造    mod   gct  20170822   start   */
       function (callbackInner) {
           logger.debug('User.update start...');
          // 删除这个字段不去更新
          if(body.user.community){delete body.user.community}

          User.update({_id: body.userID}, body.user, function (err, result) {
              if(err)
              {
                  logger.error(err.message);
                  callbackInner(err, null);
              }else{
                  logger.debug('body.isChangeCommunity...' + body.isChangeCommunity);
                  if (body.isChangeCommunity) {
                      logger.debug('http://' + AppHost + '/rest/v1.0/backOffice/setUserCommunity/' + community + '/' + body.userID);

                      restClient.get('http://' + AppHost + '/rest/v1.0/backOffice/setUserCommunity/' + community + '/' + body.userID, function (data, res) {
                          logger.debug(data.toString());
                          callbackInner(null, res);
                      }).on('error', function (err) {
                          logger.error('newQuestion:' + err.message);
                          callbackInner(err, null);
                      });
                  } else {
                      console.log("未切换小区");
                      callbackInner(null, null);
                  }
              }
          })
        },
        /*  宝宝树66小区二次改造    mod   gct  20170822   end   */
        /*  宝宝树66小区二次改造    del   gct  20170817   end   */
        //function (callbackInner) {
        //    Community.find({_id: body.user.community}, function(err, result){
        //
        //        if(result.length>0){
        //            logger.debug(result[0].isInit);
        //            if(result[0].isInit ==false){
        //
        //                QuestionStore.find({storetype: 'init'}, function (err, result) {
        //                    if (result != null && result.length > 0) {
        //                        User.findOne({mobilePhone: '66customerservice'}, 'nickName', function (err, service) {
        //                            result.forEach(function (question) {
        //                                var temp = new Question();
        //                                temp.community = body.user.community;
        //                                temp.desc = question.desc;
        //                                temp.images = question.images;
        //                                temp.category = question.category;
        //                                temp.tag = question.tag;
        //                                temp.createdBy = service._id;
        //                                temp.fromFlag = 'service';
        //                                temp.topBeginDate = new Date();
        //                                temp.topEndDate = moment().add(5, 'day').toDate();
        //                                logger.debug(temp.desc);
        //                                temp.save();
        //                            });
        //
        //                            Community.update({_id: body.user.community}, {dateEffective: new Date(), isInit: true}).exec(callbackInner);
        //                        })
        //                    };
        //                    callbackInner();
        //
        //                })
        //
        //
        //            }else{
        //                callbackInner();
        //            };
        //
        //        }else{
        //
        //            callbackInner();
        //        };
        //
        //
        //    });
        //},
    ], callback)
};

exports.updateParentsService = function (req, callback) {

    var body = req.body;
    if (!body.user) {
        return callback('body参数错误', null);
    }
    //var community = body.community;
    body.userRole = [];
    logger.debug(body);

    async.series([
        function (callbackInner) {
            UserCommunity.update({user: body.user,type:2}, body, {upsert: true},callbackInner);
        },
        function (callbackInner){
            restClient.get('http://' + AppHost + '/rest/v1.0/backOffice/initCommunity/' + body.community, function (data, res) {
                logger.debug(data.toString());
                //logger.debug(res);
                callbackInner(null, res);
            }).on('error', function (err) {
                logger.error('newQuestion:' + err.message);
                callbackInner(err, null);
            });
        }

    ], callback)
};

//
exports.isModeratorService = function (req, callback) {

    var userId = req.params.userId;
    if (!userId) {
        return callback('body参数错误', null);
    }

    User.findOne({_id: userId}, function (err, result) {
        if (!err && isModerator(result.userRole)) {
            callback();
        } else {
            callback('is not moderator...');
        }
    });
};

var isModerator = function (roleArray) {
    roleArray.each(function (temp) {
        if (temp == 1)  return true;
    });
    return false;
};

// 拉黑/取消拉黑
exports.pullBlackService = function (req, callback) {

    var body = req.body;

    if (!body.userID || body.frozenOrNot == null) {
        return callback('body参数错误', null);
    }

    var data = {frozenOrNot: body.frozenOrNot};
    if (body.reason) data.frozenReason = body.reason;

    redisClient.del(body.userID);

    User.update({_id: body.userID}, data, callback);
};


/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   start   */
// 禁言/取消禁言
exports.speakNotAllowService = function (req, callback) {

    var body = req.body;

    if (!body.userID || body.gagOrNot == null) {
        return callback('body参数错误', null);
    }

    var data = {gagOrNot: body.gagOrNot};
    if (body.reason) data.gagReason = body.reason;

    redisClient.del(body.userID);

    User.update({_id: body.userID}, data, callback);
};
/*  宝宝树66小区二次改造    add   guo.xiaomin  20170802   end   */

/*  宝宝树66小区二次改造    add   luolh  20170929   start   */
// 删除用户
exports.appUserDeleteService = function (req, callback) {
    var body = req.body;
    // 检证
    if (!body.userID || body.frozenOrNot == null) {
        return callback('body参数错误', null);
    }
    // 是否删除，删除信息
    async.series([
        function(callbackInner){
            // 取消关注我的关注
             UserFollowups.remove({'followUser': body.userID}).exec(callbackInner);
             callbackInner();
        },
        function(callbackInner){
            // 取消被我关注的信息
            UserFollowups.remove({'user': body.userID}).exec(callbackInner);
            callbackInner();
        },
        function(callbackInner){
            // 取消关注我的帖子和问题
            if (body.delUserData == true) {
                Question.find({
                    createdBy: body.userID
                }).exec(function (err, quesResults) {
                    quesResults.forEach(function (followQuestion) {
                        if (followQuestion.category == "question" || followQuestion.category == "share" || followQuestion.category == "welcome") {
                            UserFollowups.remove({question: followQuestion._id}).exec(function (error, data) {
                                if (error) {
                                    logger.error(error);
                                }
                            });
                        } else if (followQuestion.category == "activity") {
                            UserFollowups.remove({activity: followQuestion._id}).exec(function (error, data) {
                                if (error) {
                                    logger.error(error);
                                }
                            });
                        } else {
                            logger.error("其他不可牵连的类型是什么？followUser,goods:" + followQuestion.category);
                        }
                    });
                    callbackInner();
                });
            }else {
                callbackInner();
            }
        },
        function(callbackInner){
            // 取消收藏我的闲置
            if (body.delUserData == true) {
                Goods.find({
                    createdBy: body.userID
                }).exec(function (err, quesResults) {
                    quesResults.forEach(function (followQuestion) {
                        UserFollowups.remove({'goods': followQuestion._id}).exec(callbackInner);
                        redisClient.HINCRBY('goods:' + followQuestion._id + ':detail', 'collectionNum', -1);
                    });
                });
            }else {
                callbackInner();
            }
        },
        function (callbackInner) {
            // 删除此人发布的说说问问以及说说问问的评论
            // Question.update({_id: questionId}, {isValid: false}).exec(function (err, result) {
            //     callback(err, result);
            // });
            if (body.delUserData == true) {
                Question.find({
                    createdBy: body.userID
                }).exec(function (err, quesResults) {
                    // 删除帖子,包括对应的评论, 回复，调用统一的删除帖子的使用方法
                    var msg = null;
                    quesResults.forEach(function (question) {
                        restClient.delete('http://' + AppHost + '/rest/v1.0/backoffice/admin/deleteQuestion/' + question._doc._id, function (data, response) {
                            var platform=os.platform();
                            // 操作系统类型,返回值有'darwin', 'freebsd', 'linux', 'sunos' , 'win32'
                            var tokenData;

                            if (platform == "linux") {
                                tokenData = JSON.parse(data); // linux
                            } else {
                                tokenData = data;// window
                            }
                            logger.debug("platform:"+platform);
                            logger.debug(tokenData);
                            if (tokenData.result.status == 1) {
                                // 删除帖子成功
                                // callbackInner();
                            } if (tokenData.result.status == 0) {
                                // 帖子已删除，不用再删了
                                // callbackInner();
                            } else {
                                // 删除帖子失败
                                logger.debug("删除帖子,包括对应的评论, 回复等出错");
                                msg = {message:"删除帖子数据异常，请重新操作"};
                            }
                        });
                    });
                    callbackInner(msg);
                });
            } else {
                callbackInner();
            }
        },
        function (callbackInner) {
            if (body.delUserData == true) {
                Question.update({"replies.repliedBy": body.userID}, {
                    $pull: {
                        replies: {
                            repliedBy: body.userID
                        }
                    }
                }, {multi: true}).exec(callbackInner);
            } else {
                callbackInner();
            }
        },
        function (callbackInner) {
            // 删除此人在别人那的评论，回复
            // async.parallel([
            //     function (callbackInner) {
            //         // 关注数据
            //         UserFollowups.remove({'user': body.userID}, callbackInner);
            //     },
            //     function (callbackInner) {
            //         SystemMessage.remove({'fromUser': body.userID}, callbackInner);
            //     },
            //     function (callbackInner) {
            if (body.delUserData == true) {
                ugcReply.remove({repliedBy: body.userID}, callbackInner);
            } else {
                callbackInner();
            }
            // replyIndex.update({repliedBy: body.userID}, {isValid: false},{multi:true}).exec(callbackInner);
            //
            // ], function () {
            //     logger.debug('----deleteQuestionService success')
            // });
        },
        function(callbackInner){
            // 删除此人闲置评论
            if (body.delUserData == true) {
                replyIndex.remove({repliedBy : body.userID}, callbackInner);
            } else {
                callbackInner();
            }
        },
        function(callbackInner){
            // 删除此人闲置评论
            if (body.delUserData == true) {
                GoodsReply.remove({repliedBy : body.userID}, callbackInner);
            } else {
                callbackInner();
            }
        },
        function (callbackInner) {
            // 删除此人闲置
            if (body.delUserData == true) {
                Goods.update({createdBy: body.userID}, {isValid: false},{multi:true},callbackInner);
            } else {
                callbackInner();
            }
        },
        function (callbackInner) {
            // 拉黑操作
            var data = {frozenOrNot: body.frozenOrNot,gagOrNot: body.frozenOrNot};
            if (body.reason) data.frozenReason = "删除后拉黑:"+ body.reason;
            if (body.reason) data.gagReason = "删除后禁言:"+ body.reason;
            User.update({_id: body.userID}, data, function(){
                redisClient.del(body.userID);
                callbackInner();
            });

        }
    ], callback);
};
/*  宝宝树66小区二次改造    add   luolh  20170929   end   */

// 升级达人/取消达人
exports.talentService = function (req, callback) {

    var body = req.body;

    if (!body.userID || body.talent == null) {
        return callback('body参数错误', null);
    }
    if (!body.talentDesc) body.talentDesc = '';


    if (body.talent) {  // 升级达人
        User.update({_id: body.userID}, {
            'authenticationStatus': true,
            'userType': 'talent',
            'speciality': body.talentDesc
        }, callback);
    } else {    // 取消达人
        User.update({_id: body.userID}, {
            'userType': 'normalAppUser',
            'speciality': ''
        }, callback);
    }
};

// 升级V / 取消V
exports.modifyVAuthStatusService = function (req, callback) {

    var body = req.body;

    if (!(body.userID && body.communityId)) {
        return callback('body参数错误', null);
    }

    var userID = body.userID;
    var communityId = body.communityId;

    if (body.authenticationStatus == true) {
        async.series([
            function (callbackInner) {
                User.update({_id: userID}, {'authenticationStatus': body.authenticationStatus}, callbackInner);
            },
            function (callbackInner) {

                var temp = new UserAuthentication();
                temp.user = userID;
                temp.community = communityId;
                temp.status = true;
                temp.isValid = true;
                temp.refusalReason = '';
                temp.save(callbackInner)
            },
            function (callbackInner) {
                User.findOne({_id: userID}, 'invitedBy', function (err, user) {
                    callbackInner(err, user.invitedBy);
                });
            }
        ], callback);
    }
    else {

        async.series([
            function (callbackInner) {
                User.update({_id: userID}, {authenticationStatus: body.authenticationStatus}, callbackInner);
            },
            function (callbackInner) {
                UserAuthentication.findOneAndRemove({user: userID, community: communityId}, callbackInner);
            }
        ], callback);
    }
};

//
exports.eachOtherFollowupService = function (user1, user2) {

    User.find({_id: {$in: [user1, user2]}}, 'community', function (err, result) {
        if (result[0].community + '' == result[1].community + '') {
            async.parallel([
                function (callback) {
                    UserFollowups.findOne({user: user1, followUser: user2}, function (err, result) {
                        if (result == null) {
                            var temp = new UserFollowups();
                            temp.category = 'user';
                            temp.user = user1;
                            temp.followUser = user2;
                            temp.save(callback);
                        } else {
                            callback()
                        }
                    })
                },
                function (callback) {
                    UserFollowups.findOne({user: user2, followUser: user1}, function (err, result) {
                        if (result == null) {
                            var temp = new UserFollowups();
                            temp.category = 'user';
                            temp.user = user2;
                            temp.followUser = user1;
                            temp.save(callback);
                        } else {
                            callback()
                        }
                    })
                }
            ])
        }
    });
};


exports.modifyUserRoleService = function (req, callback) {

    var body = req.body;
    //var user = req.body.user._id;

    if (!(body.userID && body.communityId)) {
        return callback('body参数错误', null);
    }

    var userID = body.userID;
    var communityId = body.communityId;
    var huanxinUserName =  body.huanxinUserName;
    var userRole = [];
    var role;

    async.series([

        function (callbackInner) {

            User.findOne({_id: body.userID}, function (err, result) {
                if (result.userRole) userRole = result.userRole;
                userRole.addNonrepeat(body.userRole);
                callbackInner(err, result);
            });

        },
        function (callbackInner) {

            logger.debug(userRole);
            User.update({_id: body.userID}, {userRole: userRole}, callbackInner);
        },
        function (callbackInner) {
            UserCommunity.update({user: body.userID, community: communityId}
                , {$set: {'userRole': userRole}}, callbackInner);

        },
        //function(callbackInner){
        //
        //    var arg = {
        //        userId: body.userID + '',
        //        userRole: 1,
        //        userActionType:  19
        //    };
        //
        //    arg.__type__ = 'com.neighborhoods.service.score.dto.ScoreAddRequestDto';
        //    logger.debug(arg);
        //    scoreProxy.invoke('addScore', [arg], function (err, reply) {
        //        try {
        //            logger.debug(reply);
        //            var data = JSON.parse(decodeURIComponent(reply));
        //            if (err) {
        //                logger.error('hessianInvokeAddScore-----2' + err.message);
        //                callbackInner(null);
        //            } else if (data.status != 0) {
        //                logger.error('hessianInvokeAddScore----3' + data.status + '----' + data.msg);
        //                callbackInner(null);
        //            } else {
        //                callbackInner(null);
        //            }
        //        } catch (e) {
        //            logger.error('hessianInvokeAddScore---4' + e);
        //            callbackInner(e);
        //        }
        //    });
        //}
        //,
        function (callbackInner) {

            if(body.userRole ==3) {
                //个推
                var content = {
                    f: 8,
                    userRole: 3
                };
                var pushData = {
                    uList: [body.userID],
                    content: content
                };
                //logger.debug(pushData);
                toolUtil.putMessageTransmissionPushMQ(pushData);

                toolUtil.pushCustomerServiceMessage({_id: body.userID, huanxinUserName: huanxinUserName}, '恭喜你，成为宝宝树66小区雷锋团的一员。');

                callbackInner();
            }else{
                callbackInner();
            }
        }
    ], callback)
};


exports.rejectRoleService = function (req, callback) {

    var body = req.body;
    //var user = req.body.user._id;
    logger.debug(body);
    if (!(body.userId)) {
        return callback('body参数错误', null);
    }

    var userRole = [];
    var user;

    async.series([
        function (callbackInner) {
            User.findOne({_id: body.userId}, function (err, result) {
                user = result;
                if (result.userRole) userRole = result.userRole;
                userRole.remove(body.userRole);
                callbackInner(err, result);
            });
        },
        function (callbackInner) {
            logger.debug(userRole);
            User.update({_id: body.userId}, {userRole: userRole}, callbackInner);
        },
        function (callbackInner) {
            logger.debug(userRole);
            UserCommunity.update({user:user,community:body.community},{$set:{'userRole':userRole}}, callbackInner);
        },
        function (callbackInner) {
            if (body.message) {
                toolUtil.pushCustomerServiceMessage(user, body.message);
            }
            callbackInner();
        },
        function (callbackInner) {
            var type = 1;
            if(body.userRole ==3)type = 2;
            RoleApply.update({user: body.userId,community:body.community,status:1,type:type}, {isValid: false},{ multi: true }, callbackInner);
        },
        //function (callbackInner) {
        //
        //    //个推
        //    var content = {
        //        f: 8,
        //        userRole: 3
        //    };
        //    var pushData = {
        //        uList: [body.userId],
        //        content: content
        //    };
        //    logger.debug(pushData);
        //    toolUtil.putMessageTransmissionPushMQ(pushData);
        //
        //    callbackInner();
        //}
    ], callback)
};


exports.exportUserService = function (req, callback) {

    var body = req.cparams;
    var page = req.params.page;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var totalPage = 0;

    delete body.isValid;

    var option = body;
    var sortType = {dateCreated: -1};

    if (option.mobilePhone) option.mobilePhone = new RegExp(option.mobilePhone);
    if (option.nickName) option.nickName = new RegExp(option.nickName);


    if (body.startDate || body.endDate) {
        if (body.startDate && body.endDate) {
            if (decodeURI(body.startDate) < decodeURI(body.endDate)) {
                option.dateCreated = {$gte: decodeURI(body.startDate), $lte: decodeURI(body.endDate)};
            }
        } else if (body.startDate) {
            option.dateCreated = {$gte: decodeURI(body.startDate)};
        } else if (body.endDate) {
            option.dateCreated = {$lte: decodeURI(body.endDate)};
        }
    }
    delete option.startDate;
    delete option.endDate;

    //logger.debug(option);

    var data = null;

    async.series([
        //function (callbackInner) {
        //    User.count(option, function (err, count) {
        //
        //        totalPage = Math.ceil(count/size);
        //        var temp = {count: count, totalPage:totalPage};
        //        callbackInner(err, temp);
        //
        //    });
        //},
        function (callbackInner) {
            logger.debug(option);
            User.find(option).sort(sortType)
            //.skip(index).limit(size)
                .populate('community', '_id communityName provinceId cityId countyId communityAddress')
                .populate('domainOfExpertise', 'value')
                .populate('homeTown.country', 'name')
                .populate('homeTown.province', 'name')
                .populate('homeTown.city', 'name')
                .populate('homeTown.county', 'name')
                .populate('userPortrait', 'value')
                .exec(function (err, result) {

                    if (!err) data = result;

                    callbackInner(err, result);
                });
        },

        function (callbackInner) {

            if (data && data.length) {

                async.each(data, function (user, callbackInner2) {

                    async.series([

                        function (callbackInner3) {
                            if (!(user.community && user.community.provinceId)) {
                                callbackInner3();
                            } else {
                                Region.findOne({_id: user.community.provinceId}, function (err, result) {

                                    user.community.provinceName = result.name;

                                    callbackInner3(err, result);
                                });
                            }
                        },

                        function (callbackInner3) {
                            if (!(user.community && user.community.cityId)) {
                                callbackInner3();
                            } else {
                                Region.findOne({_id: user.community.cityId}, function (err, result) {
                                    user.community.cityeName = result.name;
                                    callbackInner3(err, result);
                                });
                            }
                        },

                        function (callbackInner3) {
                            if (!(user.community && user.community.countyId)) {
                                callbackInner3();
                            } else {
                                Region.findOne({_id: user.community.countyId}, function (err, result) {
                                    user.community.countyName = result.name;
                                    callbackInner3(err, result);
                                });
                            }
                        },

                    ], callbackInner2);

                });

            }

            callbackInner(null, data);
        },

    ], callback);

};
